//
//  PywWebPayViewController.m
//  PywSdk
//
//  Created by Jade on 16/10/20.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywWebPayViewController.h"
#import "PywMasonry.h"
#import "MutableDictionary.h"
#import "PywPaymentInfo.h"
#import "PywCPNotifications.h"
#import "UIImage+Pyw.h"
#import "ApiClientConst.h"
#import "PywAppInfo.h"

#define PYW_SCHEME @"pay.pyw.cn://"
@interface webPaySdkObj:NSObject<PaypProtocol>
@property (nonatomic,assign) UIViewController *controller;
- (instancetype)initWithController:(UIViewController *)controller;
@end
@implementation webPaySdkObj
- (instancetype)initWithController:(UIViewController *)controller
{
    self = [super init];
    if (self) {
        self.controller = controller;
    }
    return self;
}
/**
 *  退出修改页面，返回个人中心
 */
- (void)onChargeComplete
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                            object:nil];
        [weakSelf.controller.navigationController popViewControllerAnimated:YES];
    });
}

@end

@interface PywWebPayViewController ()<UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) MutableDictionary *payInfo;
@end

@implementation PywWebPayViewController

- (instancetype)initRequestPayInfo:(MutableDictionary *)payInfo
{
    self = [super init];
    if (self) {
        self.payInfo = payInfo;
    }
    return self;
}



#pragma mark - setter & getter

- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
    }
    return _webView;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addWebView];
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO; // 禁止系统的手势返回
}



- (void)returnback
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                        object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - privateMethods
- (void)addWebView
{
    [self.view addSubview:self.webView];
    __weak typeof(self) weakSelf = self;
    [weakSelf.webView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.bottom.right.left.offset(0);
    }];
    [self postParamToJS];
    
}

/**
 *  发送请求添加Param参数
 */
- (void)postParamToJS
{
    NSString *out_trade_no = [self.payInfo objectForKey:@"out_trade_no"];
    NSString *userid = [self.payInfo objectForKey:@"userid"];
    NSString *total_fee = [self.payInfo objectForKey:@"total_fee"];
    NSString *token = [self.payInfo objectForKey:@"token"];
    NSString *device_info = [self.payInfo objectForKey:@"device_info"];
    NSString *nonce_str = [self.payInfo objectForKey:@"noncestr"];
    NSString *sign = [self.payInfo objectForKey:@"sign"];
    NSString *wechat_weburl = [self.payInfo objectForKey:@"pay_url"];
    NSString *schemeStr = @"pywsdkdemoweixin";
    
    if ([PywAppInfo sharedAppInfo].sdk_pay_url.length > 0) {
        wechat_weburl = [PywAppInfo sharedAppInfo].sdk_pay_url;
    }
    NSString *wxUrl = wechat_weburl.length> 0?wechat_weburl:webH5PayUrl;
    NSString *requestUrl = [NSString stringWithFormat:@"%@?out_trade_no=%@&userid=%@&total_fee=%@&token=%@&device_info=%@&nonce_str=%@&sign=%@&schemeStr=%@",wxUrl,out_trade_no,userid,total_fee,token,device_info,nonce_str,sign,schemeStr];
    PLog(@"requestUrl:%@",requestUrl);
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]
                                                  cachePolicy:NSURLRequestReloadIgnoringCacheData
                                              timeoutInterval:20];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    request = [mutableRequest copy];
    canLoad = YES;
    [self.webView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //JS-->:window.sdkObj.doSdkExit 接收JS调用OC
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"exceptionValue:%@", exceptionValue);
    };
    webPaySdkObj *sdkObj = [[webPaySdkObj alloc] initWithController:self];
    context[@"sdkObj"] = sdkObj;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


NSString *dynamicReferer;
//从微信返回后，会迷之重新访问wx_checkout,用此变量判断是否已经完成一次h5支付流程(跳转去微信后，至下次下单)
BOOL canLoad = NO;
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *wxpurl = @"wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb";
    if ([request.URL.absoluteString containsString:wxpurl]){
        NSString *newUrl = request.URL.absoluteString;
        BOOL changeURL = NO;
        if([newUrl containsString:@"redirect_url"]){
            NSMutableString *muString = [NSMutableString new];
            //进行字符串的拆分，通过&来拆分，把每个参数分开
            NSArray *subArray = [newUrl componentsSeparatedByString:@"&"];
            for(int i=0;i<subArray.count;i++){
                if(![subArray[i] containsString:@"redirect_url"]){
                    [muString appendString:subArray[i]];
                    [muString appendString:@"&"];
                }else{
                    NSArray *array = [subArray[i] componentsSeparatedByString:@"="];
                    dynamicReferer = [NSURL URLWithString:[self URLDecodedString:array[1]]].host;
                }
            }
            NSRange deleteRange = {[muString length] - 1, 1};
            [muString deleteCharactersInRange:deleteRange];
            newUrl = [NSString stringWithString:muString];
            changeURL = YES;
        }
        NSDictionary *headers = [request allHTTPHeaderFields];
        NSString *sReferer = [headers objectForKey:@"Referer"];
        BOOL needReferer = sReferer==nil?YES:![sReferer isEqualToString:dynamicReferer];
        if(changeURL || needReferer){
            NSURL *url = [NSURL URLWithString:newUrl];
            NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
            [request setHTTPMethod:@"GET"];
//            [request setValue:PYW_SCHEME forHTTPHeaderField: @"Referer"];
            [request setValue:dynamicReferer forHTTPHeaderField: @"Referer"];
            [webView loadRequest:request];
            return NO;
        }
    }
    if([request.URL.scheme isEqualToString:@"weixin"]){
        [[UIApplication sharedApplication] openURL:request.URL options:@{} completionHandler:nil];
        canLoad = NO;
        return NO;
    }
    if(!canLoad){
        [self returnback];
        return NO;
    }
    return YES;
}


-(NSString *)URLDecodedString:(NSString *)str
{
    if(str==nil) return @"";
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
